package com.maixy.dailydemo.algorithm;

/**
 * @ClassName MyTest2
 * @Description 反转链表 II
 * 给你单链表的头指针 head 和两个整数left 和 right ，其中left <= right 。
 * 请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。
 *
 * @Date 2021/4/27 14:53
 * @Author maixy
 */
public class MyTest2 {
    public class ListNode {

        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {this.val = val;}
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        String s ="11";

        char[] arr = s.toCharArray();
        //因为头节点有可能发生变化，使用虚拟头节点可以避免复杂的分类讨论
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;

        //从虚拟节点周left-1步，来到left节点的前一个节点
        ListNode pre = dummyNode;
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }

        //从pre再走right-left+1步来到right节点
        ListNode rightNode = pre;
        for (int i = 0; i < right - left + 1; i++) {
            rightNode = rightNode.next;
        }

        //切断出一个子链表
        ListNode leftNode = pre.next;
        ListNode curr = rightNode.next;

        //切断连接
        pre.next = null;
        rightNode.next = null;

        reverserLinkedList(leftNode);

        pre.next = rightNode;
        leftNode.next = curr;
        return dummyNode.next;
    }

    public void reverserLinkedList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (null != curr) {
            ListNode nodeTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nodeTemp;
        }
    }

}
